package com.tencent.qcloud.tim.uikit.modules.group.role

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.manor.common.utils.StringUtil
import com.manor.common.utils.ToastUtil
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMGroupMemberFullInfo
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.qcloud.tim.uikit.R
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.bean.RoleEvent
import com.tencent.qcloud.tim.uikit.component.dialog.TUIKitDialog
import com.tencent.qcloud.tim.uikit.component.picture.imageEngine.impl.GlideEngine
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfo
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfoActivity
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfoProvider
import com.tencent.qcloud.tim.uikit.modules.group.member.GroupMemberInfo
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants
import kotlinx.android.synthetic.main.group_set_admin_activity.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *
 * @version 1.0

 * @date 2020/7/31  17:43
 */
public class SetAdminActivity : Activity() {
    private var groupId = ""
    private var mDataList = mutableListOf<GroupMemberInfo>()
    private var mAdapter: MAdapter? = null
    private var mProvider: GroupInfoProvider? = null
    private var mGroupInfo: GroupInfo? = null

    companion object {

        fun forward(context: Context, groupId: String) {
            Intent(context, SetAdminActivity::class.java).apply {
                this.putExtra(TUIKitConstants.Group.GROUP_ID, groupId);
                context.startActivity(this)
            }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.group_set_admin_activity)
        groupId = intent?.getStringExtra(TUIKitConstants.Group.GROUP_ID) ?: ""
        if (StringUtil.isEmpty(groupId))
            finish()
        initView()
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    private fun initView() {
        mProvider = GroupInfoProvider()
        doGroupInfo()

        mAdapter = MAdapter(R.layout.item_set_admin, mDataList)
        mRecycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mRecycler.adapter = mAdapter

        ivBack.setOnClickListener { finish() }
        tvAdd.setOnClickListener { goAdd() }
        mAdapter?.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tvCancel)
                showCancelAdmin(adapter.data[position] as GroupMemberInfo)
        }
    }


    private fun doGroupInfo() {
        mProvider?.run {


            loadGroupInfo(groupId,object : IUIKitCallBack{
                override fun onSuccess(data: Any?) {
                    this@SetAdminActivity.mGroupInfo = this@run.mGroupInfo
                    var list: MutableList<GroupMemberInfo>? =   this@run.groupMembers

                    list = list?.filter {
                        it.memberType == V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_ADMIN
                    }?.toMutableList()

                    list?.let {
                        mAdapter?.setNewInstance(it)
                        mAdapter?.notifyDataSetChanged()
                    }

                }

                override fun onError(module: String?, errCode: Int, errMsg: String?) {
                    errMsg?.let { ToastUtil.show(it) }
                }

            })

        }
    }



    private fun goAdd() {
        mGroupInfo?.let {
            val groupInfo = it
            groupInfo.memberDetails = groupInfo.memberDetails.filter { itx ->
                itx.memberType == V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_MEMBER
            }
            GroupInfoActivity.forward(this, it)
        }

    }


    private fun showCancelAdmin(info: GroupMemberInfo) {
        val groupId = mGroupInfo?.id
        if (StringUtil.isEmpty(groupId)) return
        var name: String = info.nameCard
        if (StringUtil.isEmpty(name.trim { it <= ' ' })) {
            name = info.nickName
        }
        TUIKitDialog(this)
                .builder()
                .setCancelable(true)
                .setCancelOutside(true)
                .setTitle("您将取消" + name + "的管理员身份?")
                .setDialogWidth(0.75f)
                .setPositiveButton("确定") {
                    V2TIMManager.getGroupManager()
                            .setGroupMemberRole(groupId,
                                    info.userId,
                                    V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_MEMBER,
                                    object : V2TIMCallback {
                                        override fun onError(i: Int, s: String) {
                                            ToastUtil.show("操作失败")
                                        }

                                        override fun onSuccess() {
                                            //ToastUtil.show("修改成功")
                                            doGroupInfo()
                                        }
                                    })
                }
                .setNegativeButton("取消") { }
                .show()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun doRefresh(e: RoleEvent) {
        if (e.needRefresh) {
            doGroupInfo()
        }
    }


    private class MAdapter(layoutResId: Int, data: MutableList<GroupMemberInfo>)
        : BaseQuickAdapter<GroupMemberInfo, BaseViewHolder>(layoutResId, data) {

        init {
            addChildClickViewIds(R.id.tvCancel)
        }

        override fun convert(holder: BaseViewHolder, item: GroupMemberInfo) {
            GlideEngine.loadCircleImage(holder.getView(R.id.ivImg), item.iconUrl)
            holder.setText(R.id.tvText, if (StringUtil.isNotEmpty(item.nameCard)) item.nameCard else item.nickName)
        }

    }


}